<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Bootstrap core CSS -->
<link href="${ctx}/openmonitor/jui/asserts/bootstrap-3.3.0/css/bootstrap.min.css" rel="stylesheet">
<!--lib js  -->
<script type="text/javascript" src="${ctx}/openmonitor/jui/asserts/jquery-1.11.3/jquery.min.js"></script>
<!-- js加载器 -->
<script type="text/javascript" src="${ctx}/openmonitor/jui/dest/core/jui.config.js"></script>
<script type="text/javascript" src="${ctx}/openmonitor/jui/dest/loader/loader.js"></script>
<style type="text/css">
body {margin: 10px;}
.sch td{padding-left: 10px;}
.limit-open{color: green;}
.limit-close{color: red;}
.color-red {color:red;}
.limit-readonly{background-color:#eee;border:1px solid #ccc;}
#limitWin table th {width: 160px;text-align: right;}
span.error{font-size: 12px;color:red;margin-left: 5px;}
.opt-bar{margin-bottom: 5px;}
</style>
</head>
<body>
<form id="frmSch">
    <table>
        <tr>
            <td>接口名：<input id="apiName" name="name" type="text" placeholder="支持模糊查询"/> 
                                        开启状态：<select name="status">
                    <option value="">-全部-</option>
                    <option value="1">开启</option>
                    <option value="0">关闭</option>
                    </select>
                                        策略：<select name="limitType">
                    <option value="">-全部-</option>
                    <option value="LIMIT">漏桶策略</option>
                    <option value="TOKEN_BUCKET">令牌桶策略</option>
                    </select>
            <button class="btn-primary" onclick="search();" type="button">查询(Enter)</button>
            </td>
        </tr>
    </table>
</form>
<hr>

<div class="opt-bar">
    <button id="batchOpen" class="btn-info" type="button">批量开启</button>
    <button id="batchClose" class="btn-warning" type="button">批量关闭</button>
</div>

<div id="grid"></div>

<div id="limitWin">
	<form id="frmBase">
	    <table class="table table-bordered">
	       <tr>
                <th>接口名：</th><td><input name="name" type="text" class="limit-readonly" readonly="readonly"/></td>
            </tr>
            <tr>
                <th>版本号：</th><td><input name="version" type="text" class="limit-readonly" readonly="readonly"/></td>
            </tr>
            <tr>
                <th>策略：</th>
                <td> 
                    <label><input name="limitType" class="limit-type" type="radio" value="LIMIT"/> 漏桶策略</label>
                    <label><input name="limitType" class="limit-type" type="radio" value="TOKEN_BUCKET"/> 令牌桶策略</label>
                </td>
            </tr>
            <tr>
                <th>状态：</th>
                <td> 
                    <label class="limit-open"><input name="status" class="limit-status" type="radio" value="1"/> 开启</label>
                    <label class="limit-close"><input name="status" class="limit-status" type="radio" value="0"/> 关闭</label>
                </td>
            </tr>
	    </table>
	    </form>
	    <div id="limitArea">
		    <fieldset id="LIMIT_ID">
			    <legend>漏桶策略</legend>
			    <h5>每秒处理固定数量的请求，超出请求返回错误信息。</h5>
			    <form id="frmLimit">
			    <table class="table table-bordered">
		           <tr>
		                <th>每秒处理请求数：</th><td>
		                <input id="limitCount" name="limitCount" type="text" 
		                   rules="[{rule:{positiveInt:true,notNull:true},successMsg:'',errorMsg:'请输入正整数'}
		                           ,{rule:{maxLength:8},successMsg:'',errorMsg:'长度不得超过8位'}]"
		                   onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"/></td>
		            </tr>
		            <tr>
		                <th>限制后返回code：</th><td><input id="limitCode" name="limitCode" type="text" 
		                   rules="[{rule:{notNull:true},successMsg:'',errorMsg:'请输入code'}
	                               ,{rule:{maxLength:50},successMsg:'',errorMsg:'长度不得超过50'}]"
		                /></td>
		            </tr>
		            <tr>
		                <th>限制后返回msg：</th><td><input id="limitMsg" name="limitMsg" type="text" style="width: 320px;"
		                   rules="[{rule:{notNull:true},successMsg:'',errorMsg:'请输入msg'}
	                               ,{rule:{maxLength:50},successMsg:'',errorMsg:'长度不得超过100'}]"
		                /></td>
		            </tr>
		        </table>
		        </form>
			</fieldset>
			
		    <fieldset style="display: none;">
	            <legend>令牌桶策略</legend>
	            <h5>每秒放置固定数量的令牌数，不足的令牌数做等待处理，直到拿到令牌为止。</h5>
	            <form id="frmToken">
	            <table class="table table-bordered">
		           <tr>
		                <th>令牌桶容量：</th><td>
		                <input name="tokenBucketCount" type="text" 
		                   rules="[{rule:{positiveInt:true,notNull:true},successMsg:'',errorMsg:'请输入正整数'}
	                               ,{rule:{maxLength:8},successMsg:'',errorMsg:'长度不得超过8位'}]"
		                   onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" /></td>
		            </tr>
		        </table>
		        </form>
	        </fieldset> 
	    </div>
	
</div>


<script type="text/javascript">
var jq = jQuery;
var tokenRemark = '令牌桶策略：每秒放置固定数量的令牌数，不足的令牌数做等待处理，直到拿到令牌为止。';
var limitRemark = '漏桶策略：每秒处理固定数量的请求，超出请求返回错误信息。';
var LimitType = {
	    LIMIT:'LIMIT',TOKEN_BUCKET:'TOKEN_BUCKET'
}

/*
 * 表格控件：https://gitee.com/durcframework/jui
 */
JUI
.dir('${ctx}/openmonitor/jui/dest/') // 设置JS存放根目录
.use(['Grid','DialogForm'],function(){
	grid = new JUI.Grid({
		renderId:'grid'
		,url:'${url}/data'
		,rownumbers:true // 显示行索引
		,hover:true // 移动高亮
		,striped:false // 斑马线,默认true
		,pagination :true
        ,pageSize:100
        ,pageList:[0,10,20,50,100,200,500,1000]
		,onLoadSuccess:function(e) {
			// 无权限
			if(e.data == -1) {
				location.href = 'limit?q=' + new Date().getTime();
			} else if(e.data.code) {
				JUI.Msg.alert('错误', '数据请求错误:' + e.data.msg);
			}
		}
		,columns : [[
			{field:'name',checkbox : true} ,// 勾选
			{field : 'name',title : '接口名'},
			{field : 'version',title : '版本号'},
			{field : 'limitCount',title : '每秒可处理请求数',sortable:true, formatter:function(val,obj,index){
                return obj.limitType == LimitType.LIMIT ? val : '-';
            }},
            {field : 'msg',title : 'code/msg',width:300, formatter:function(val,obj,index){
                return obj.limitType == LimitType.LIMIT ? (obj.limitCode || '<span class="color-red">未设置</span>') + '/' + (obj.limitMsg || '<span class="color-red">未设置</span>') : '-';
            }},
			{field : 'tokenBucketCount',title : '令牌桶容量',sortable:true, formatter:function(val,obj,index){
                return obj.limitType != LimitType.LIMIT ? val : '-';
            }},
			{field : 'status',title : '开启状态' ,sortable:true, formatter:function(val,obj,index){
                return val == 1 ? '<span class="limit-open">开启</span>' : '<span class="limit-close">关闭</span>';
            }},
			{field : 'limitType',title : '限流策略[<a href="#" onclick="showLimitType(); return false;">?</a>]',formatter:function(val,obj,index){
                return val == LimitType.LIMIT ? '<span title="'+limitRemark+'">漏桶策略</span>' : '<span title="'+tokenRemark+'">令牌桶策略</span>';
            }},
            
            {field : '_opt',title : '操作',formatter:function(val,obj,index){
                var html = [];
                var setBtn = '<button class="btn-set btn-info">设置</button>';
                	
                html.push(setBtn);
                
                return html.join(' ');
            }},
		]]
	});
	
	grid.on('ClickCell',function(e){
        var target = $(e.target); // $target即<a>
                
        if(target.hasClass('btn-set')) {
            var row = e.row;
            limitWin.setData(row);
            frmLimit.setData(row);
            frmToken.setData(row);
            displayLimitTypeFieldset(row.limitType);
            displayLimitTypeArea(row.status);
            limitWin.show();
        }
    });
	
	
	frmSch = new JUI.Form({
        formId:'frmSch'
    });
	frmLimit = new JUI.Form({
        formId:'frmLimit'
    });
	frmToken = new JUI.Form({
        formId:'frmToken'
    });
	
	
	limitWin = new JUI.DialogForm({
        contentId:'limitWin'
        ,formId:'frmBase'
        ,title:'设置'
        ,width:500
        ,onOk:function() {
            this.submit({
            	url:'${url}/modify'
                ,onSubmit:function(data) {
                	if(data.status == 0) {
                		return true;
                	}
                	var validateRet = true;
                	if(data.limitType == LimitType.LIMIT) {
                		validateRet = frmLimit.validate();
                		if(validateRet) {
                			jq.extend(data, frmLimit.getData());
                		}
                	} else {
                		validateRet = frmToken.validate();
                		if(validateRet) {
                            jq.extend(data, frmToken.getData());
                        }
                	}
                    return validateRet;
                }
                ,success:function(data) {
                	if(data.code) {
                        JUI.Msg.alert('错误', data.msg);
                    } else {
                    	limitWin.hide();
                        search();
                    }
                }
            });
        }
    });

});

function search() {
	grid.load(frmSch.getData());
}

$('#frmSch').keyup(function(e){
	if(e.keyCode == 13) {
		search();
	}
	return false;
}).keydown(function(e){if(e.keyCode == 13) {return false;}});

$('.limit-type').click(function(){
	displayLimitTypeFieldset(this.value);
});

$('.limit-status').click(function(){
	displayLimitTypeArea(this.value);
});

$('#batchOpen').click(function(){
	batchStatus(1);
});

$('#batchClose').click(function(){
	batchStatus(0);
});

function batchStatus(status) {
	var datas = grid.getChecked();
	if(datas.length == 0) {
		JUI.Msg.alert('提示', '请勾选接口');
		return;
	}
	JUI.Msg.confirm('确认','确认要批量' + (status == 1 ? '开启':'关闭') + '操作吗？',function(r){
		if(r) {
		    var data = {status:status};
		    var nameVersionList = [];
	        for(var i=0,len=datas.length; i<len; i++) {
	            nameVersionList.push(datas[i].nameVersion);
	        }
	        data.nameVersionList = nameVersionList;
            
            jq.ajax({
                type: 'post',
                url: '${url}/status',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (data, textStatus, jqXHR) {
                    search();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    JUI.Msg.alert('提示','删除数据错误');
                }
            });
		}
	});
}

function displayLimitTypeFieldset(limitType) {
	if(limitType == LimitType.LIMIT) {
        $('#LIMIT_ID').show().siblings('fieldset').hide();
    } else {
        $('#LIMIT_ID').hide().siblings('fieldset').show();
    }
}

function displayLimitTypeArea(status) {
	if(status == 1) {
	    $('#limitArea').show();		
	} else {
	    $('#limitArea').hide();		
	}
}

function showLimitType() {
	JUI.Msg.alert('策略说明',limitRemark + '<br>' + tokenRemark);
}
</script>
</body>
</html>